package cn.springcloud.fix.quartz.config;

import cn.springcloud.fix.quartz.dao.entity.SysJob;
import cn.springcloud.fix.quartz.dao.mapper.SysJobMapper;
import cn.springcloud.fix.quartz.util.QuartzUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.List;

/**
 * Quartz配置类
 */
@Slf4j
@Configuration
public class QuartzConfig {

    @Autowired
    private SysJobMapper sysJobMapper;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(QuartzManager quartzManager) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setStartupDelay(2);
        schedulerFactoryBean.setAutoStartup(true);
        schedulerFactoryBean.setJobFactory((triggerFiredBundle, scheduler) -> quartzManager);
        // schedulerFactoryBean.afterPropertiesSet();
        // schedulerFactoryBean.start();
        return schedulerFactoryBean;
    }

    @Bean
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean, SchedulerSupport schedulerSupport) throws Exception {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        scheduler.getContext().put("xx", "oo");
        scheduler.getListenerManager().addSchedulerListener(schedulerSupport);
        this.createJob(scheduler);
        return scheduler;
    }

    private void createJob(Scheduler scheduler) {
        //从数据库读取定时任务
        List<SysJob> sysJobList = sysJobMapper.selectList(Wrappers.<SysJob>lambdaQuery().ne(SysJob::getJobStatus, -1));
        if (CollectionUtils.isNotEmpty(sysJobList)) {
            for (SysJob sysJob : sysJobList) {
                QuartzUtil.createScheduleJob(scheduler, QuartzManager.class, sysJob.getId(), sysJob.getJobGroup(), sysJob.getCronExpression());
            }
        }
    }
}
